package com.itheima.controller;

import com.itheima.common.R;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/11/3 10:55
 */

@RestController
@RequestMapping("/common")
public class UploadeController {
    @Value("${reggie.path}")
    private String basefilePath;

    /**
     * 将上传文件保存到服务器
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R<String> uploade(MultipartFile file) throws IOException {
        // 获取上传文件名称
        String originalFilename = file.getOriginalFilename();
        // 获取文件的后缀名FilenameUtils
        String extension = FilenameUtils.getExtension(originalFilename);
        String uuid = UUID.randomUUID().toString();
        String fileName = uuid+"."+extension;
        // 将文件保存在指定位置
        file.transferTo(new File(basefilePath,fileName));
        return R.success(fileName);
    }

    @GetMapping("/download")
    public R<String> download(String name, HttpServletResponse response) throws IOException {
        FileInputStream fis = new FileInputStream(new File(basefilePath, name));
        ServletOutputStream ops = response.getOutputStream();
        IOUtils.copy(fis, ops);
        return R.success("下载成功！");
    }
}
